package com.flot.yazb.home.moudle.message;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flot.yazb.R;
import com.flot.yazb.base.BActivity;
import com.flot.yazb.base.BApplication;
import com.flot.yazb.base.model.BModel;
import com.flot.yazb.aop.stub.CodeStub;
import com.flot.yazb.db.MessageDapImpl;
import com.flot.yazb.model.fate.FateModel;
import com.flot.yazb.model.nearly.TranslatingModel;
import com.flot.yazb.model.user.UserModel;
import com.flot.yazb.model.user.ZhuboDetailModel;
import com.flot.yazb.home.setting.UserDetailActivity;
import com.flot.yazb.home.moudle.message.adapter.ChatMessageAdapter;
import com.flot.yazb.widget.utils.GlideImageLoaderUtil;
import com.flot.yazb.widget.utils.IsNullOrEmpty;
import com.flot.yazb.widget.utils.KeyBoardUtil;
import com.flot.yazb.widget.utils.TimeUtils;
import com.flot.yazb.widget.utils.ToastUtil;
import com.flot.yazb.widget.RoundedImageView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 聊天界面
 * Created by fengdongfei on 2017/9/14.
 */

public class ChatActivity extends BActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tltit)
    RelativeLayout tltit;
    @BindView(R.id.lv_message)
    ListView lvMessage;
    @BindView(R.id.divider)
    View divider;
    @BindView(R.id.iv_send_msg)
    ImageView ivSendMsg;
    @BindView(R.id.et_msg)
    EditText etMsg;
    @BindView(R.id.ll_msg)
    LinearLayout llMsg;
    @BindView(R.id.rl_msg)
    RelativeLayout rlMsg;
    @BindView(R.id.icon)
    RoundedImageView icon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.job)
    TextView job;
    @BindView(R.id.beizhu)
    TextView beizhu;


    private List<TranslatingModel> msgList = new ArrayList<>();
    private ChatMessageAdapter msgAdapter;
    private UserModel meModel = BApplication.getInstance().getUserModel();
    private MessageDapImpl msgDao;
    private String mid;
    private TranslatingModel cachedModel;
    private String thump;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        String name = getIntent().getStringExtra("name");
        mid = getIntent().getStringExtra("mid");
        cachedModel = (TranslatingModel) getIntent().getSerializableExtra("cached");
        msgList.clear();
        tvName.setText(name);
        //数据库操作
        msgDao = new MessageDapImpl(ChatActivity.this);
        initListener();
        getData();
    }

    /**
     * 获取主播信息
     */
    public ZhuboDetailModel anchorModel;

    private void getData() {
        ZhuboDetailModel.getUserDetail(mid, new BModel.Transit<ZhuboDetailModel>(this) {

            @Override
            public void onBorn(ZhuboDetailModel serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK) && serializable != null) {
                    anchorModel = serializable;
                    if (serializable.imgs.size() > 0)
                        GlideImageLoaderUtil.loadImage(icon, serializable.imgs.get(0).thumb);
                    name.setText(serializable._$0.name);
                    job.setText(serializable._$0.job);
                    beizhu.setText(serializable._$0.beizhu);
                    if (serializable.imgs.size() > 0)
                        thump = serializable.imgs.get(0).thumb;
                    initData();
                }
            }
        });
    }

    private void initListener() {
        lvMessage.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                KeyBoardUtil.hideKeyboard(ChatActivity.this);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
    }

    private void initData() {

        msgAdapter = new ChatMessageAdapter(this, msgList,thump);
        lvMessage.setAdapter(msgAdapter);
        lvMessage.setSelection(msgAdapter.getCount());
        if (cachedModel != null && cachedModel.cachedList != null && cachedModel.cachedList.size() > 0) {
            msgList.clear();
            msgList.addAll(cachedModel.cachedList);
            msgAdapter.notifyDataSetChanged();
            lvMessage.setSelection(cachedModel.cachedList.size() - 1);
        } else {
            requestApiByRetrofit(100);
        }

    }


    @OnClick({R.id.iv_back, R.id.iv_send_msg, R.id.icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_send_msg:

                sendMessage();
                break;
            case R.id.icon:
                FateModel par = new FateModel();
                par.mid = anchorModel._$0.mid;
                par.name = anchorModel._$0.name;
                par.thumb = anchorModel.imgs.get(0).thumb;
                par.age = anchorModel._$0.age;
                Intent intent = new Intent(this, UserDetailActivity.class);
                intent.putExtra("mid", par);
                startActivity(intent);
                break;
        }
    }

    public void sendMessage() {
        String msg = etMsg.getText().toString().trim();
        if (!IsNullOrEmpty.isEmpty(msg)) {
            TranslatingModel entity = new TranslatingModel(ChatMessageAdapter.TYPE_RIGHT, TimeUtils.getCurrentTimeMillis() + "", msg);
            msgList.add(entity);
            msgAdapter.notifyDataSetChanged();
            etMsg.setText("");
            lvMessage.setSelection(msgList.size() - 1);
//            add(entity);
            requestApiByRetrofit(3000);
        }
    }


    private void requestApiByRetrofit(final int time) {
        TranslatingModel.transPeople(meModel.id, new BModel.Transit<TranslatingModel[]>(activity) {
            @Override
            public void onBorn(final TranslatingModel[] serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    if (serializable != null) {
                        if (serializable.length > 0) {
                            Random random = new Random();
                            final int x = random.nextInt(serializable.length);
                            if (x < serializable.length) {
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        TranslatingModel nm = new TranslatingModel(ChatMessageAdapter.TYPE_LEFT,
                                                TimeUtils.getCurrentTimeMillis() + "", serializable[x].content);
                                        nm.isShowPic = false;
                                        msgList.add(nm);
                                        msgAdapter.notifyDataSetChanged();
                                        serializable[x].time = TimeUtils.getCurrentTimeMillis() + "";
                                        serializable[x].type = ChatMessageAdapter.TYPE_LEFT;
                                        serializable[x].isShowPic = true;
                                        msgList.add(serializable[x]);
                                        msgAdapter.notifyDataSetChanged();
                                        lvMessage.setSelection(msgList.size() - 1);
//                                    add(serializable[0]);
                                    }
                                }, time);
                            }
                        }
                    }
                } else {
                    ToastUtil.showToast(activity, message);
                }
            }
        });

    }

    public static CachedListener mCachedListener;

    public interface CachedListener {
        void cache(List<TranslatingModel> list, String id);
    }

    public static void setOnCachedListener(CachedListener listener) {
        mCachedListener = listener;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mCachedListener != null)
            mCachedListener.cache(msgList, mid);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void add(TranslatingModel modle) {
        Long Id = msgDao.insert(modle);
    }

    public void get_one(Long id) {
        TranslatingModel smodel = msgDao.get(id.intValue());
    }


    public List findAll() {
        List<TranslatingModel> list = msgDao.find();
        for (TranslatingModel model : list) {
            list.add(model);
        }
        return list;
    }

    public List findSelect(String mid, Long id) {
        List<TranslatingModel> list = msgDao.find(new String[]{"mid", "selfid"},
                " mid =  " + mid, new String[]{id.toString()}, null, null,
                null, null);
        for (TranslatingModel model : list) {
            list.add(model);
        }
        return list;
    }

    public List findBySql(String id1, String id2) {
        List<TranslatingModel> list = msgDao.rawQuery(
                "SELECT * FROM t_msg WHERE mid=? and selfid=? ", new String[]{
                        id1, id2});
        for (TranslatingModel model : list) {
            list.add(model);
        }
        return list;
    }


    public void update(TranslatingModel model) {
        msgDao.update(model);
    }


    public void delByArray(Long id1, Long id2, Long id3) {
        msgDao.delete(id1.intValue());
        msgDao.delete(new Integer[]{id2.intValue(), id3.intValue()});
    }

    public void delById(Long id) {
        msgDao.delete(id.intValue());
    }
}
